package com.qf.commons.core.listener;

import org.slf4j.MDC;
import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.event.GenericApplicationListener;
import org.springframework.core.Ordered;
import org.springframework.core.ResolvableType;
import org.springframework.core.env.ConfigurableEnvironment;

/**
 * 监听SpringBoot环境准备事件，进行相应的处理 - 设置MDC
 * @author YaoJiXing
 * created 2022/8/16 20:58
 */
public class LogMDCHandlerListener implements GenericApplicationListener {

    /**
     * 程序监听所支持的事件类型
     * @param eventType the event type (never {@code null})
     * @return ApplicationEnvironmentPreparedEvent.class
     */
    @Override
    public boolean supportsEventType(ResolvableType eventType) {
        return eventType.isAssignableFrom(ApplicationEnvironmentPreparedEvent.class);
    }

    /**
     * @param sourceType the source type, or {@code null} if no source
     * @return true
     * 如果返回的是true，表示会处理这个事件类型，就会触发 onApplicationEvent 这个方法
     * 如果返回的是false，表示不会处理这个事件类型，就不会触发 onApplicationEvent 这个方法
     */
    @Override
    public boolean supportsSourceType(Class<?> sourceType) {
        return true;
    }

    /**
     * 事件处理方法
     * @param event the event to respond to
     */
    @Override
    public void onApplicationEvent(ApplicationEvent event) {
        //强制转成 环境准备条件
        ApplicationEnvironmentPreparedEvent preparedEvent = (ApplicationEnvironmentPreparedEvent) event;
        //获得当前的环境
        ConfigurableEnvironment environment = preparedEvent.getEnvironment();
        //获得微服务的名称
        String serviceName = environment.getProperty("spring.application.name");
        //设置 MDC
        MDC.put("fileName", serviceName);
    }

    @Override
    public int getOrder() {
        //设置优先级高于log4j2的监听器
        //public static final int DEFAULT_ORDER = Ordered.HIGHEST_PRECEDENCE + 20;
        return Ordered.HIGHEST_PRECEDENCE + 19;
    }
}
